import network
import socket
import time


def start(mode = 'STA',essid ='meik30',password = '5201314ygyu'):
    if mode == 'AP':
        nic = network.WLAN(network.AP_IF)
    elif mode == "STA":
        nic = network.WLAN(network.STA_IF)
        nic.active(True)         # 激活 
    if mode == 'AP':
        nic.config(essid = essid,password = password) # 设置热点名字，密码
    elif mode == "STA":
        nic.connect(essid, password) # 设置连接WIFI名字，密码
    while not nic.isconnected():
        time.sleep(1)
    print('network config:', nic.ifconfig())
    return nic

def server(mode = "UDP",addr = ('0.0.0.0', 7788)):
    if mode == 'TCP'or mode == 'tcp':
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(addr)
        sock.listen(10)
        print(999)
        link = sock.accept()
        print(999)
        return link[0]

    elif mode == 'UDP' or mode == 'udp':
        sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        print("link complete... ")
        sock.bind(addr)
        return sock

